This page was generated from source/notebooks/L5/interactive-map-folium.ipynb.
Binder badge
Binder badge CSC badge

Interactive maps on Leaflet

JavaScript (JS) is a programming language which is mostly used for adding interactive content (such a zoomamble maps!) on webpages.

Whenever you go into a website that has some kind of interactive map, it is quite probable that you are wittnessing a map that has been made with a JavaScipt library called Leaflet. Another popular JavaSCript library is called OpenLayers.

In this lesson, we will learn how to publish interactive online maps using Python and Leaflet. In spesific, we will have a look at two different libraries; Folium and mplleaflet which both allow you to create interactive maps (using the Leaflet JavaScript library) after manipulating data in Python.

Folium

Folium is a Python library that makes it possible visualize data on an interactive Leaflet map.

Resources:

Creating a simple interactive web-map

Let’s first see how we can do a simple interactive web-map without any data on it. We just visualize OpenStreetMap on a specific location of the a world.

  • First thing that we need to do is to create a Map instance. There are few parameters that we can use to adjust how in our Map instance that will affect how the background map will look like.
In [2]:
import folium

# Create a Map instance
m = folium.Map(location=[60.25, 24.8],
    zoom_start=10, control_scale=True)

The first parameter location takes a pair of lat, lon values as list as an input which will determine where the map will be positioned when user opens up the map. zoom_start -parameter adjusts the default zoom-level for the map (the higher the number the closer the zoom is). control_scale defines if map should have a scalebar or not.

  • Let’s see what our map looks like:
In [3]:
m
Out[3]:
  • We can also save the map already now
  • Let’s save the map as a html file base_map.html:
In [4]:
outfp = "results/base_map.html"
m.save(outfp)

TASK: Navigate to the location where you saved the html file and open it in a web browser (preferably Google Chrome). Open the file also in a text editor to see the source script.

  • Let’s change the basemap style to Stamen Toner and change the location of our map slightly. The tiles -parameter is used for changing the background map provider and map style (see the documentation for all in-built options).
In [5]:
# Let's change the basemap style to 'Stamen Toner'
m = folium.Map(location=[40.730610, -73.935242], tiles='Stamen Toner',
                zoom_start=12, control_scale=True, prefer_canvas=True)

m
Out[5]:

TASK: Modify the codeblock above and visualize a couple of different maps with different parameters (bacground maps, zoom levels etc). See documentation of class folium.folium.Map() for all avaiable options.

Adding layers to the map

Let’s first have a look how we can add a simple marker on the webmap:

In [6]:
# Create a Map instance
m = folium.Map(location=[60.20, 24.96],
    zoom_start=12, control_scale=True)

# Add marker
# Run: help(folium.Icon) for more info about icons
folium.Marker(
    location=[60.20426, 24.96179],
    popup='Kumpula Campus',
    icon=folium.Icon(color='green', icon='ok-sign'),
).add_to(m)

#Show map
m
Out[6]:

As mentioned, Folium combines the strenghts of data manipulation in Python with the mapping capabilities of Leaflet.js. Eventually, we would like to first manipulate data using Pandas/Geopandas before creating a fancy map.

Let’s first practice by adding the address points (locations of transport stations) onto the Helsinki basemap: - read input points using Geopandas:

In [7]:
import geopandas as gpd

# File path
points_fp = r"data/addresses.shp"

# Read the data
points = gpd.read_file(points_fp)

#Check input data
points.head()
Out[7]:
address id geometry
0 Kampinkuja 1, 00100 Helsinki, Finland 1001 POINT (24.9301701 60.1683731)
1 Kaivokatu 8, 00101 Helsinki, Finland 1002 POINT (24.9418933 60.1698665)
2 Hermanstads strandsväg 1, 00580 Helsingfors, F... 1003 POINT (24.9774004 60.18735880000001)
3 Itäväylä, 00900 Helsinki, Finland 1004 POINT (25.0919641 60.21448089999999)
4 Tyynenmerenkatu 9, 00220 Helsinki, Finland 1005 POINT (24.9214846 60.1565781)
In [8]:
# Convert points to GeoJson
points_gjson = folium.features.GeoJson(points, name = "Public transport stations")

Now we have our population data stored as GeoJSON format which basically contains the data as text in a similar way that it would be written in the .geojson -file.

  • add the points onto the Helsinki basemap
In [9]:
# Create a Map instance
m = folium.Map(location=[60.25, 24.8], tiles = 'cartodbpositron', zoom_start=10, control_scale=True)

# Add points to the map instance
points_gjson.add_to(m)

# Alternative syntax for adding points to the map instance
#m.add_child(points_gjson)

#Show map
m
Out[9]:

Heatmap

Folium plugins allow us to use popular plugins available in leaflet. One of these plugins is HeatMap, which creates a heatmap layer from input points.

Let’s visualize a heatmap of the public transport stations in Helsinki using the addresses input data. folium.plugins.HeatMap requires a list of points, or a numpy array as input, so we need to first manipulate the data a bit:

In [10]:
# Get lat and lon coordinates
points['lon'] = points["geometry"].x
points['lat'] = points["geometry"].y

# Conver lat and lon to numpy array (old method: .as_matrix())
points_array = points[['lat', 'lon']].values

Check the output:

In [11]:
print(type(points_array))
print(points_array[:5])
<class 'numpy.ndarray'>
[[60.1683731 24.9301701]
 [60.1698665 24.9418933]
 [60.1873588 24.9774004]
 [60.2144809 25.0919641]
 [60.1565781 24.9214846]]
In [12]:
from folium.plugins import HeatMap

# Create a Map instance
m = folium.Map(location=[60.25, 24.8], tiles = 'stamentoner', zoom_start=10, control_scale=True)

# Add heatmap to map instance
# Available parameters: HeatMap(data, name=None, min_opacity=0.5, max_zoom=18, max_val=1.0, radius=25, blur=15, gradient=None, overlay=True, control=True, show=True)
HeatMap(points_array).add_to(m)

# Alternative syntax:
#m.add_child(HeatMap(points_array, radius=15))

# Show map
m
Out[12]:

Choroplet map

Next, let’s check how we can overlay a population map on top of a basemap using folium’s choropleth method. This method is able to read the geometries and attributes directly from a geodataframe. This example is modified from the Folium quicksart.

  • First download the population grid data following instructions from lesson 3
  • Read the data using Geopandas
In [13]:
# Filepaths
fp = "data/Pop17/Vaestoruudukko_2017.shp"

# Read Data
data = gpd.read_file(fp)

# Check the data
data.head()
Out[13]:
INDEX ASUKKAITA ASVALJYYS IKA0_9 IKA10_19 IKA20_29 IKA30_39 IKA40_49 IKA50_59 IKA60_69 IKA70_79 IKA_YLI80 geometry
0 688 9 28.0 99 99 99 99 99 99 99 99 99 POLYGON Z ((25472499.99532626 6689749.00506918...
1 710 8 44.0 99 99 99 99 99 99 99 99 99 POLYGON Z ((25472499.99532626 6684249.00413040...
2 711 5 90.0 99 99 99 99 99 99 99 99 99 POLYGON Z ((25472499.99532626 6683999.00499700...
3 715 12 37.0 99 99 99 99 99 99 99 99 99 POLYGON Z ((25472499.99532626 6682998.99846143...
4 848 6 44.0 99 99 99 99 99 99 99 99 99 POLYGON Z ((25472749.99291839 6690249.00333598...
  • re-project layer into WGS 84 (epsg: 4326)
  • Modify columns:
In [14]:
# Re-project to WGS84
data = data.to_crs(epsg=4326)

# Check layer crs definition
print(data.crs)

# Make a selection (only data above 0 and below 1000)
data = data.loc[(data['ASUKKAITA'] > 0) & (data['ASUKKAITA'] <= 1000)]

# Create a Geo-id which is needed by the Folium (it needs to have a unique identifier for each row)
data['geoid'] = data.index.astype(str)

# Select only needed columns
data = data[['geoid', 'ASUKKAITA', 'geometry']]

# Convert to geojson (not needed for the simple coropleth map!)
#pop_json = data.to_json()

#check data
data.head()
{'no_defs': True, 'init': 'epsg:4326'}
Out[14]:
geoid ASUKKAITA geometry
0 0 9 POLYGON Z ((24.50236241370834 60.3192786485171...
1 1 8 POLYGON Z ((24.50311210582754 60.2699165231241...
2 2 5 POLYGON Z ((24.50314612020954 60.2676727893988...
3 3 12 POLYGON Z ((24.50328212493893 60.2586977569763...
4 4 6 POLYGON Z ((24.50681848707329 60.3237829367646...
In [15]:
# Create a Map instance
m = folium.Map(location=[60.25, 24.8], tiles = 'cartodbpositron', zoom_start=10, control_scale=True)

# Plot a choropleth map
# Notice: 'geoid' column that we created earlier needs to be assigned always as the first column
folium.Choropleth(
    geo_data=data,
    name='Population in 2017',
    data=data,
    columns=['geoid', 'ASUKKAITA'],
    key_on='feature.id',
    fill_color='YlOrRd',
    fill_opacity=0.7,
    line_opacity=0.2,
    line_color='white',
    line_weight=0,
    highlight=False,
    smooth_factor=1.0,
    #threshold_scale=[100, 250, 500, 1000, 2000],
    legend_name= 'Population in Helsinki').add_to(m)

#Show map
m
Out[15]:

Tooltips

It is possible to add different kinds of pop-up messages and tooltips to the map. Here, it would be nice to see the population of each grid cell when you hover the mouse over the map. Unfortunately this functionality is not apparently implemented implemented in the Choropleth method we used before.

Add tooltips, we can add tooltips to our map when plotting the polygons as GeoJson objects using the GeoJsonTooltip feature. (folliwing examples from here and here)

For a quick workaround, we plot the polygons on top of the coropleth map as a transparent layer, and add the tooltip to these objects. Note: this is not an optimal solution as now the polygon geometry get’s stored twice in the output!

In [16]:
# Convert points to GeoJson
folium.features.GeoJson(data,  name='Labels',
               style_function=lambda x: {'color':'transparent','fillColor':'transparent','weight':0},
                tooltip=folium.features.GeoJsonTooltip(fields=['ASUKKAITA'],
                                              aliases = ['Population'],
                                              labels=True,
                                              sticky=False
                                             )
                       ).add_to(m)

m
Out[16]:

Rember that you can also save the output as an html file:

In [17]:
outfp = "results/choropleth_map.html"
m.save(outfp)

Clustered point map

Let’s visualize the address points (locations of transport stations in Helsinki) on top of the choropleth map using clustered markers.

In [18]:
from folium.plugins import MarkerCluster

# Create a Clustered map where points are clustered
marker_cluster = MarkerCluster().add_to(m)
In [19]:
# Create clustered points on top of the map
for idx, row in points.iterrows():
    # Get lat and lon of points
    lon = row['geometry'].x
    lat = row['geometry'].y

    # Get address informatin
    address = row['address']

    # Add marker to the marker cluster
    folium.RegularPolygonMarker(location=[lat, lon], popup=address, fill_color='#2b8cbe', number_of_sides=6, radius=8).add_to(marker_cluster)
In [20]:
#Show map:
m
Out[20]:

Layer control

We can also add a LayerControl object on our map, which allows the user to control which map layers are visible. See the documentation for available parameters (you can e.g. change the position of the layer control icon).

In [21]:
# Create a layer control object and add it to our map instance
folium.LayerControl().add_to(m)

#Show map
m
Out[21]:

From matplotlib to leaflet using mllpleaflet

We can also convert maptlotlib plots directly to interactive web maps using mllpleaflet.

All you need to do is to:

  1. visualize your data using matplotlib (or geodataframe.plot())
  2. convert the plot into a webmap using mplleaflet.show()

Let’s demonstrate this using the static map we plotted earler in this lesson

In [22]:
import geopandas as gpd
import matplotlib.pyplot as plt
import mplleaflet
In [23]:
# 1.Plot data:
points.plot()

# 2. Convert plot to a web map:
mplleaflet.show()

(the code above opens up a new tab with the visualized map)

We can also render the map insite the notebook (following this example):

In [24]:
# 1. Plot data:
ax = points.plot(markersize = 50, color = "red")

# 2. Convert plot to a web map:
mplleaflet.display(fig=ax.figure, crs=points.crs)
Out[24]:

TASK: create a map using your geopandas/matplotlib skills and convert it into a webmap using mplleaflet.show()